package edu.gzhu.guli.front.service.impl;

import com.aliyuncs.utils.StringUtils;
import edu.gzhu.guli.core.common.ApplicationResult;
import edu.gzhu.guli.core.entity.Comment;
import edu.gzhu.guli.core.entity.CourseOrder;
import edu.gzhu.guli.core.entity.Member;
import edu.gzhu.guli.core.repository.CommentRepository;
import edu.gzhu.guli.core.repository.CourseOrderRepository;
import edu.gzhu.guli.core.repository.MemberRepository;
import edu.gzhu.guli.front.dto.CommentInfoDto;
import edu.gzhu.guli.front.dto.CourseInfoDto;
import edu.gzhu.guli.front.dto.CourseOrderInfoDto;
import edu.gzhu.guli.front.dto.MemberInfoDto;
import edu.gzhu.guli.front.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Slf4j
@Tag(name = "用户接口")
public class UserServiceImpl implements UserService {

    @Autowired
    private MemberRepository memberRepository;

    @Autowired
    private CourseOrderRepository courseOrderRepository;

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private ModelMapper modelMapper;

    private final BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

    @Override
    public ApplicationResult<MemberInfoDto> getMemberInfoById(Long id, MemberInfoDto memberInfoDto) {
        Optional<Member> memberOptional = memberRepository.findById(id);
        if (!memberOptional.isPresent())
            return ApplicationResult.failure("未找到ID为: " + id + "的用户信息");
        Member member = memberOptional.get();
        modelMapper.map(member, memberInfoDto);
        log.info("封装用户基本信息:{}", memberInfoDto);
        List<CourseInfoDto> courseInfoDtoList = member.getCourses()
                .stream()
                .map(memberJoinCourse -> modelMapper.map(memberJoinCourse.getCourse(), CourseInfoDto.class))
                .collect(Collectors.toList());
        log.info("封装用户参与课程信息:{}", courseInfoDtoList);
        memberInfoDto.setCourseInfoDtoList(courseInfoDtoList);
        List<CourseOrder> courseOrderList = courseOrderRepository.findCourseOrderByMemberId(id);
        List<CourseOrderInfoDto> courseOrderInfoDtoList = courseOrderList
                .stream()
                .map(courseOrder -> modelMapper.map(courseOrder, CourseOrderInfoDto.class))
                .collect(Collectors.toList());
        memberInfoDto.setCourseOrderInfoDtoList(courseOrderInfoDtoList);
        log.info("封装课程订单信息:{}", courseOrderInfoDtoList);
        return ApplicationResult.succese(memberInfoDto);
    }

    @Override
    public ApplicationResult<CommentInfoDto> userComment(CommentInfoDto commentInfoDto) {
        if (StringUtils.isEmpty(commentInfoDto.getContent()))
            return ApplicationResult.failure("评论内容不能为空");
        Comment comment = modelMapper.map(commentInfoDto, Comment.class);
        comment = commentRepository.save(comment);
        modelMapper.map(comment, commentInfoDto);
        return ApplicationResult.succese(commentInfoDto);
    }

    @Operation(summary = "用户注册")
    @Override
    public ApplicationResult<MemberInfoDto> userRegister(MemberInfoDto memberInfoDto) {
        if (!StringUtils.isEmpty(memberInfoDto.getUsername()) && !StringUtils.isEmpty(memberInfoDto.getPassword())) {
            Optional<Member> optionalMember = memberRepository.findByUsername(memberInfoDto.getUsername());
            if (!optionalMember.isPresent()){
                // 密码加密
                memberInfoDto.setPassword(bCryptPasswordEncoder.encode(memberInfoDto.getPassword()));
                Member member = modelMapper.map(memberInfoDto, Member.class);
                memberRepository.save(member);
                return ApplicationResult.succese();
            }
            else{
                return ApplicationResult.failure("用户名已被占用");
            }
        }
        return ApplicationResult.failure("用户名或者密码不存在");
    }

    @Override
    public ApplicationResult<MemberInfoDto> userUpdate(MemberInfoDto memberInfoDto) {
        Member member = memberRepository.findByUsername(memberInfoDto.getUsername()).get();
        member.setPassword(bCryptPasswordEncoder.encode(memberInfoDto.getPassword()));
        member.setAvatar(memberInfoDto.getAvatar());
        member.setPhone(memberInfoDto.getPhone());
        member.setName(memberInfoDto.getName());
        // 如果密码被修改
        if (!memberInfoDto.getPassword().equals(member.getPassword())){
            member.setAvatar(bCryptPasswordEncoder.encode(memberInfoDto.getPassword()));
        }
        memberRepository.save(member);
        member = memberRepository.findByUsername(member.getUsername()).get();
        return ApplicationResult.succese(modelMapper.map(member,MemberInfoDto.class));
    }
}
